HTML 5 Game Development - Tutorial step 4


Ok, in this last step we'll add the last bits.

First of all, we need to detect if the Monster is "touching" the Player so that it can inflict damages

  update() {
	//
    
    //now inflict damages
    inflictDamages();
    
    //clean player command list for the next loop
    lastComands.clear();
  }
  
  void inflictDamages() {
    if (p.x <= (m.x + MONSTER_IMAGE_X)
        && m.x <= (p.x + HERO_IMAGE_X)
        && p.y <= (m.y + MONSTER_IMAGE_Y)
        && m.y <= (p.y + HERO_IMAGE_Y)
    ) {
      //print("you will be slaved!!");
      p.decreaseHealth();
    }
    else {
      //dont touch
      //print("dont touch at the moment");
    }
  }

Then let's add a monster clock to trace its time to live.

void drawClock(CanvasRenderingContext2D context, num value) {
  num valueToDraw = value/TIME_TO_LIVE;
  context..beginPath()
  ..moveTo(550, 40)
  ..arc(550, 40, 20, PI * -0.5, PI * (-0.5 + 2 * valueToDraw), true)
  ..lineTo(550, 40)
  ..closePath()
  ..fillStyle = value > TIME_TO_LIVE/2 ? "red" : "green"
  ..fill();
}

Let's block the monster and the player from going over tha canvas.

  @override
  void applyCommands(List l) {
    for(Command c in l) {
      if(c != null) {
        switch (c) {
          case Command.NORTH:
            y = max(0, y-PLAYER_MOVEMENT);
            break;
          case Command.SOUTH:
            y = min(y+PLAYER_MOVEMENT, HEIGHT - HERO_IMAGE_Y);
            break;
          case Command.EAST:
            x = min(x+PLAYER_MOVEMENT, WIDTH - HERO_IMAGE_X);
            break;
          case Command.WEST:
            x = max(0,x-PLAYER_MOVEMENT);
            break;
        } 
      }
    }
  }

This will block the user from "going" outside the boundaries of the canvas. We need also to modify the random positions for the Player and Monster at the start of the game

  Character.Dimension(int dimX, int dimY) {
    x = r.nextInt(WIDTH - dimX);
    y = r.nextInt(HEIGHT - dimY);
  }
  
  //
  Player() : super.Dimension(HERO_IMAGE_X, HERO_IMAGE_Y);
  
  //
  Monster() : super.Dimension(MONSTER_IMAGE_X, MONSTER_IMAGE_Y);
  

Tada!! Finished (not really, but for the purpose of this demo definitevely). Check the full game Demo

I'm building a more "realistic" game; a clone of SuperPang with multiplayer and WebRTC comunication...keep waiting
Theme Sponsored by: Roller Blinds, Cyprus Holidays, Walk in Baths